package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.WlConfigFieldssettingMapper;
import com.ysd.lis.mapper.lab.WlConfigMapper;
import com.ysd.lis.mapper.lab.WlConfigPatsettingMapper;
import com.ysd.lis.mapper.lab.WlConfigResultssettingMapper;
import com.ysd.lis.request.wl.WlConfigParam;
import com.ysd.lis.service.lab.WlConfigFieldssettingService;
import com.ysd.lis.service.lab.WlConfigPatsettingService;
import com.ysd.lis.service.lab.WlConfigResultssettingService;
import com.ysd.lis.service.lab.WlConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验报告-信息配置 服务实现类
 * </p>
 *
 * @author WangHao
 * @since 2024-01-18
 */
@Service
public class WlConfigServiceImpl extends ServiceImpl<WlConfigMapper, WlConfig> implements WlConfigService {

    @Autowired
    private WlConfigMapper wlConfigMapper;

    @Autowired
    private WlConfigService wlConfigService;
    @Autowired
    private WlConfigPatsettingMapper wlConfigPatsettingMapper;
    @Autowired
    private WlConfigPatsettingService wlConfigPatsettingService;

    @Autowired
    private WlConfigResultssettingMapper wlConfigResultssettingMapper;
    @Autowired
    private WlConfigResultssettingService wlConfigResultssettingService;

    @Autowired
    private WlConfigFieldssettingMapper configFieldssettingMapper;
    @Autowired
    private WlConfigFieldssettingService configFieldssettingService;

    /**
     * 默认选中
     */
    public static final Integer IS_DEFAULT = 1;

    @Override
    public Result findWlConfig(WlConfigParam wlConfigParam) {
        if (StringUtils.isBlank(wlConfigParam.getSuitModule())) {
            wlConfigParam.setSuitModule("1");//默认普通检验类别
        }

        /*默认数据*/
        MPJLambdaWrapper<WlConfig> lambdaQueryDefWrapper = new MPJLambdaWrapper<>();
        lambdaQueryDefWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryDefWrapper.eq(WlConfig::getIsDefault, IS_DEFAULT);
        lambdaQueryDefWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
        lambdaQueryDefWrapper.orderByAsc(WlConfig::getDisplayOrder);
        List<WlConfig> defList = wlConfigMapper.selectList(lambdaQueryDefWrapper);

        /*报告单元特有数据*/
        //根据报告单元查询配置信息,并且查询默认的配置,排序先默认后根据顺序号
        MPJLambdaWrapper<WlConfig> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(WlConfig.class);
        lambdaQueryWrapper.selectAs(LabRptGroup::getRptGroupName, WlConfig::getRptGroupName);
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, WlConfig::getRptGroup);
        lambdaQueryWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
        lambdaQueryWrapper.eq(WlConfig::getRptGroup, wlConfigParam.getRptGroup());
        lambdaQueryWrapper.ne(WlConfig::getIsDefault, IS_DEFAULT);
        //lambdaQueryWrapper.and(wrapper -> wrapper.eq(WlConfig::getRptGroup, wlConfigParam.getRptGroup()).and().ne(WlConfig::getIsDefault, IS_DEFAULT));
        if (StringUtils.isNotBlank(wlConfigParam.getFilter())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(WlConfig::getCode, wlConfigParam.getFilter()).or().like(WlConfig::getName, wlConfigParam.getFilter()));
        }
        //lambdaQueryWrapper.orderByDesc(WlConfig::getIsDefault);
        lambdaQueryWrapper.orderByAsc(WlConfig::getDisplayOrder);
        List<WlConfig> wlConfigs = wlConfigMapper.selectList(lambdaQueryWrapper);

        List<WlConfig> resList = new ArrayList<>(defList);//defList.addAll(wlConfigs);
        resList.addAll(wlConfigs);
        return Result.succ(1, "查询成功", resList);
    }

    @Override
    public Result copyWlConfig(OrganizationDTO input) {
        String sourceOrgId = input.getSourceOrgId();
        String goalOrgId = input.getGoalOrgId();
        Integer orgIndex = input.getOrgIndex();
        String s = AlphabetArray.Alphabet[orgIndex];
        /*默认数据*/
        MPJLambdaWrapper<WlConfig> lambdaQueryDefWrapper = new MPJLambdaWrapper<>();
        lambdaQueryDefWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryDefWrapper.eq(WlConfig::getSuitModule, input.getSuitModule());
        lambdaQueryDefWrapper.eq(WlConfig::getOrgId, sourceOrgId);
        List<WlConfig> defList = wlConfigMapper.selectList(lambdaQueryDefWrapper);


        //删除数据库历史
        wlConfigMapper.delete(new LambdaQueryWrapper<WlConfig>().eq(WlConfig::getOrgId, goalOrgId).eq(WlConfig::getSuitModule, input.getSuitModule()));
        List<WlConfig> copyConfigs = new ArrayList<>();
        List<WlConfigPatsetting> wlConfigPatsets = new ArrayList<>();
        List<WlConfigResultssetting> resultssettings = new ArrayList<>();
        List<WlConfigFieldssetting> fieldssettings = new ArrayList<>();
        for (WlConfig wlConfig : defList) {
            WlConfig copyConfig = new WlConfig();
            BeanUtil.copyProperties(wlConfig, copyConfig, "id", "orgId");
            String id = wlConfig.getId();
            String newId = s + id.substring(s.length());
            copyConfig.setId(newId);
            copyConfig.setOrgId(goalOrgId);
            copyConfigs.add(copyConfig);

            wlConfigPatsettingMapper.delete(new LambdaQueryWrapper<WlConfigPatsetting>().eq(WlConfigPatsetting::getOrgId, goalOrgId).eq(WlConfigPatsetting::getWlConfigId, newId));
            LambdaQueryWrapper<WlConfigPatsetting> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WlConfigPatsetting::getDelFlag, 0);
            lambdaQueryWrapper.eq(WlConfigPatsetting::getWlConfigId, id);
            List<WlConfigPatsetting> wlConfigPatsettings = wlConfigPatsettingMapper.selectList(lambdaQueryWrapper);
            for (WlConfigPatsetting wlConfigPatsetting : wlConfigPatsettings) {
                WlConfigPatsetting copyPatsetting = new WlConfigPatsetting();
                BeanUtil.copyProperties(wlConfigPatsetting, copyPatsetting, "id", "wlConfigId", "orgId");
                String patsettingId = wlConfigPatsetting.getId();
                String newPatsettingId = s + patsettingId.substring(s.length());
                copyPatsetting.setId(newPatsettingId);
                copyPatsetting.setWlConfigId(newId);
                copyPatsetting.setOrgId(goalOrgId);
                wlConfigPatsets.add(copyPatsetting);
            }

            wlConfigResultssettingMapper.delete(new LambdaQueryWrapper<WlConfigResultssetting>().eq(WlConfigResultssetting::getOrgId, goalOrgId).eq(WlConfigResultssetting::getWlConfigId, newId));
            LambdaQueryWrapper<WlConfigResultssetting> resultWrapper = new LambdaQueryWrapper<>();
            resultWrapper.eq(WlConfigResultssetting::getDelFlag, 0);
            resultWrapper.eq(WlConfigResultssetting::getWlConfigId, id);
            List<WlConfigResultssetting> wlConfigResultssettings = wlConfigResultssettingMapper.selectList(resultWrapper);
            for (WlConfigResultssetting wlConfigResultssetting : wlConfigResultssettings) {
                WlConfigResultssetting copyResultsetting = new WlConfigResultssetting();
                BeanUtil.copyProperties(wlConfigResultssetting, copyResultsetting, "id", "wlConfigId", "orgId");
                String resultsettingId = wlConfigResultssetting.getId();
                String newResultsettingId = s + resultsettingId.substring(s.length());
                copyResultsetting.setId(newResultsettingId);
                copyResultsetting.setWlConfigId(newId);
                copyResultsetting.setOrgId(goalOrgId);
                resultssettings.add(copyResultsetting);
            }
            configFieldssettingMapper.delete(new LambdaQueryWrapper<WlConfigFieldssetting>().eq(WlConfigFieldssetting::getOrgId, goalOrgId).eq(WlConfigFieldssetting::getWlConfigId, newId));
            LambdaQueryWrapper<WlConfigFieldssetting> fieldSettingWrapper = new LambdaQueryWrapper<>();
            fieldSettingWrapper.eq(WlConfigFieldssetting::getDelFlag, 0);
            fieldSettingWrapper.eq(WlConfigFieldssetting::getWlConfigId, id);
            List<WlConfigFieldssetting> wlConfigFieldssettings = configFieldssettingMapper.selectList(fieldSettingWrapper);
            for (WlConfigFieldssetting wlConfigFieldssetting : wlConfigFieldssettings) {
                WlConfigFieldssetting copyFieldsetting = new WlConfigFieldssetting();
                BeanUtil.copyProperties(wlConfigFieldssetting, copyFieldsetting, "id", "wlConfigId", "orgId");
                String fieldsettingId = wlConfigFieldssetting.getId();
                String newFieldsettingId = s + fieldsettingId.substring(s.length());
                copyFieldsetting.setId(newFieldsettingId);
                copyFieldsetting.setWlConfigId(newId);
                copyFieldsetting.setOrgId(goalOrgId);
                fieldssettings.add(copyFieldsetting);
            }

        }
        wlConfigService.saveBatch(copyConfigs);
        wlConfigPatsettingService.saveBatch(wlConfigPatsets);
        wlConfigResultssettingService.saveBatch(resultssettings);
        configFieldssettingService.saveBatch(fieldssettings);
        return null;
    }

    @Override
    public Result findWlConfigSizeAndHeight(WlConfigParam wlConfigParam) {
        if (StringUtils.isBlank(wlConfigParam.getRptGroup())) {
            wlConfigParam.setSuitModule("1");//默认普通检验类别
        }

        /*默认数据*/
        MPJLambdaWrapper<WlConfig> lambdaQueryDefWrapper = new MPJLambdaWrapper<>();
        lambdaQueryDefWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryDefWrapper.eq(WlConfig::getIsDefault, IS_DEFAULT);
        lambdaQueryDefWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
        lambdaQueryDefWrapper.orderByAsc(WlConfig::getDisplayOrder);
        List<WlConfig> defList = wlConfigMapper.selectList(lambdaQueryDefWrapper);

        //根据报告单元查询配置信息,并且查询默认的配置,排序先默认后根据顺序号
        LambdaQueryWrapper<WlConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
        lambdaQueryWrapper.eq(WlConfig::getRptGroup, wlConfigParam.getRptGroup());
        lambdaQueryWrapper.ne(WlConfig::getIsDefault, IS_DEFAULT);
        lambdaQueryWrapper.orderByAsc(WlConfig::getDisplayOrder);
        List<WlConfig> wlConfigs = wlConfigMapper.selectList(lambdaQueryWrapper);

        /*优先级判断*/
        if (wlConfigs.isEmpty()) {
            if (!defList.isEmpty()) {
                return Result.succ(1, "查询成功", defList.get(0));
            }
            return Result.succ(1, "查询成功", null);
        } else {
            return Result.succ(1, "查询成功", wlConfigs.get(wlConfigs.size() - 1));
        }
        /*if (CollectionUtils.isEmpty(wlConfigs)) {
            LambdaQueryWrapper<WlConfig> isDefaultQueryWrapper = new LambdaQueryWrapper<>();
            isDefaultQueryWrapper.eq(WlConfig::getDelFlag, 0);
            isDefaultQueryWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
            isDefaultQueryWrapper.eq(WlConfig::getIsDefault, IS_DEFAULT);
            List<WlConfig> configList = wlConfigMapper.selectList(isDefaultQueryWrapper);
            return Result.succ(1, "查询成功", configList.get(0));
        } else {
            return Result.succ(1, "查询成功", wlConfigs.get(0));
        }*/
    }

    @Override
    public Result insertOrUpdateConfigsting(List<WlConfig> wlConfigs) {
        boolean b = false;
        for (WlConfig wlConfig : wlConfigs) {
            b = this.saveOrUpdate(wlConfig);
        }
        if (b) {
            return Result.succ(1, "成功", null);
        } else {
            return Result.fail(400, "失败", "");
        }
    }

    @Override
    public Result batchDeleteConfigsting(List<WlConfig> wlConfigParam) {
        List<String> ids = wlConfigParam.stream().map(WlConfig::getId).collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result findWlConfigByRptGroup(WlConfigParam wlConfigParam) {

        LambdaQueryWrapper<WlConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WlConfig::getDelFlag, 0);
        lambdaQueryWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());

        lambdaQueryWrapper.eq(WlConfig::getRptGroup, wlConfigParam.getRptGroup());
        lambdaQueryWrapper.orderByAsc(WlConfig::getDisplayOrder);
        List<WlConfig> wlConfig = wlConfigMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(wlConfig)) {
            lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WlConfig::getDelFlag, 0);
            lambdaQueryWrapper.eq(WlConfig::getSuitModule, wlConfigParam.getSuitModule());
            lambdaQueryWrapper.eq(WlConfig::getIsDefault, IS_DEFAULT);
            lambdaQueryWrapper.orderByAsc(WlConfig::getDisplayOrder);
            WlConfig wlConfigDefault = wlConfigMapper.selectOne(lambdaQueryWrapper);
            if (ObjectUtils.isNull(wlConfigDefault)) {
                return Result.succ(1, "查询成功", new ArrayList<>());
            } else {
                wlConfig.add(wlConfigDefault);
            }
        }
        switch (wlConfigParam.getType()) {
            case 1:
                LambdaQueryWrapper<WlConfigPatsetting> patWrapper = new LambdaQueryWrapper<>();
                patWrapper.eq(WlConfigPatsetting::getDelFlag, 0);
                patWrapper.eq(WlConfigPatsetting::getWlConfigId, wlConfig.get(0).getId());
                patWrapper.orderByAsc(WlConfigPatsetting::getDisplayOrder);
                List<WlConfigPatsetting> wlConfigPatsettings = wlConfigPatsettingMapper.selectList(patWrapper);
                List<WlConfigPatsetting> patsettings = wlConfigPatsettings.stream().filter(m -> m.getIsVisiable().equals(1)).collect(Collectors.toList());
                return Result.succ(1, "查询成功", patsettings);
            case 2:
                LambdaQueryWrapper<WlConfigResultssetting> resultWrapper = new LambdaQueryWrapper<>();
                resultWrapper.eq(WlConfigResultssetting::getDelFlag, 0);
                resultWrapper.eq(WlConfigResultssetting::getWlConfigId, wlConfig.get(0).getId());
                resultWrapper.orderByAsc(WlConfigResultssetting::getDisplayOrder);
                List<WlConfigResultssetting> wlConfigResultssettings = wlConfigResultssettingMapper.selectList(resultWrapper);
                List<WlConfigResultssetting> resultssettings = wlConfigResultssettings.stream().filter(m -> m.getIsVisiable().equals(1)).collect(Collectors.toList());
                return Result.succ(1, "查询成功", resultssettings);
            case 3:
                LambdaQueryWrapper<WlConfigFieldssetting> fieldWrapper = new LambdaQueryWrapper<>();
                fieldWrapper.eq(WlConfigFieldssetting::getDelFlag, 0);
                fieldWrapper.eq(WlConfigFieldssetting::getWlConfigId, wlConfig.get(0).getId());
                fieldWrapper.orderByAsc(WlConfigFieldssetting::getDisplayOrder);
                List<WlConfigFieldssetting> wlConfigFieldssettings = configFieldssettingMapper.selectList(fieldWrapper);
                List<WlConfigFieldssetting> fieldssettings = wlConfigFieldssettings.stream().filter(m -> m.getIsVisiable().equals(1)).collect(Collectors.toList());

                return Result.succ(1, "查询成功", fieldssettings);
            default:
                return Result.succ(1, "查询成功", new ArrayList<>());
        }

    }

}
